package com.xquant.databasemanagement.controller.panel;


import com.xquant.databasemanagement.bean.DatabaseBean;
import com.xquant.databasemanagement.config.Config;
import com.xquant.databasemanagement.config.ConstantConfig;
import com.xquant.databasemanagement.controller.panel.left.LeftPanelController;
import com.xquant.databasemanagement.service.*;
import freemarker.template.TemplateException;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.scene.control.MenuItem;
import javafx.scene.control.TreeItem;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Pane;
import javafx.stage.DirectoryChooser;
import javafx.stage.FileChooser;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;


public class MainPanelController implements Initializable {


    @FXML
    private MenuItem createIncrementMySQLButton;
    @FXML
    private MenuItem elseSaveDatabase;
    @FXML
    private MenuItem crateDatabase;

    @FXML
    private MenuItem openDatabase;

    @FXML
    private MenuItem saveDatabase;

    @FXML
    private MenuItem returnButton;

    @FXML
    private MenuItem createIncrementOracleSqlButton;
    @FXML
    private BorderPane mainPanel;

    @FXML
    private Pane bottom;

    @FXML
    private Pane leftPanel;


    private CompareService compareService;

    private XMLService xmlService;

    @FXML
    private LeftPanelController leftPanelController;

    private TransformTreeItemService transformTreeItemService;




    @FXML
    private void openFile(ActionEvent event) throws IOException {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择数据版本文件");
        fileChooser.getExtensionFilters().addAll( new FileChooser.ExtensionFilter("XML", "*.xml"));
        File file = fileChooser.showOpenDialog(mainPanel.getScene().getWindow());
        if (file!=null) {
            Config.databaseURL = file.getParent();
            Config.databaseName = file.getName();
            Config.isOpenData = true;
            DatabaseBean databaseModel = xmlService.openXMLFile(file.getParent(),file.getName());
            if (databaseModel != null) {
                transformTreeItem(databaseModel);
                mainPanel.setLeft(leftPanel);
                Config.databaseModel = databaseModel;
            }


        }

    }

    @FXML
    private void crateDatabase(ActionEvent event){
        if (Config.isOpenData){
            Config.databaseModel = new DatabaseBean();
            Config.databaseName = null;
            Config.databaseURL = null;
            leftPanelController.clearControl();
            mainPanel.setCenter(null);
        }
        Config.isOpenData = true;
        mainPanel.setLeft(leftPanel);
    }

    @FXML
    private void saveFile(ActionEvent event) throws IOException {
        if (Config.isOpenData) {
            if(Config.databaseURL==null&&Config.databaseName==null) {
                FileChooser fileChooser = new FileChooser();
                fileChooser.setTitle("选择保存路径");
                fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XML", "*.xml"));
                File file = fileChooser.showSaveDialog(mainPanel.getScene().getWindow());
                Config.databaseName = file.getName();
                Config.databaseURL = file.getParent();
            }
            setDatabaseModel(Config.databaseModel);
            xmlService.saveXMLFile(Config.databaseModel,Config.databaseURL,Config.databaseName);
        }

    }
    @FXML
    private void elseSaveFile(ActionEvent event) throws IOException {
        FileChooser fileChooser = new FileChooser();
        fileChooser.setTitle("选择保存路径");
        fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XML", "*.xml"));
        File file = fileChooser.showSaveDialog(mainPanel.getScene().getWindow());
        if (file!=null) {
            Config.databaseName = file.getName();
            Config.databaseURL = file.getParent();
            setDatabaseModel(Config.databaseModel);
            xmlService.saveXMLFile(Config.databaseModel,file.getParent(),file.getName());
        }
    }

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        xmlService = XMLService.getXmlService();
        transformTreeItemService = TransformTreeItemService.getTransformTreeItemService();
    }

    /**
     * 将treeView中的值赋给Config.databaseModel对象
     * @param databaseModel
     */
    private void setDatabaseModel(DatabaseBean databaseModel){
        databaseModel.transformTableList((ObservableList<TreeItem>) leftPanelController.table.getChildren());
        databaseModel.transformViewList((ObservableList<TreeItem>) leftPanelController.view.getChildren());
        databaseModel.transformBasicDataList((ObservableList<TreeItem>) leftPanelController.basicData.getChildren());
        databaseModel.transformFunctionList((ObservableList<TreeItem>) leftPanelController.function.getChildren());
        databaseModel.transformTriggerList((ObservableList<TreeItem>) leftPanelController.trigger.getChildren());
        databaseModel.transformSequenceList((ObservableList<TreeItem>) leftPanelController.sequence.getChildren());
        databaseModel.transformProcedureList((ObservableList<TreeItem>) leftPanelController.procedure.getChildren());
    }


    @FXML
    private void compareDatabase(ActionEvent event) throws IOException {
        if (Config.databaseName==null)
            saveFile(new ActionEvent());
        if (Config.isOpenData) {
            setDatabaseModel(Config.databaseModel);
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择数据版本文件");
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("XML", "*.xml"));
            File file = fileChooser.showOpenDialog(mainPanel.getScene().getWindow());
            if (file != null) {
                setDisable(true);
                DatabaseBean databaseModel = xmlService.openXMLFile(file.getParent(), file.getName());
                compareService = CompareService.getCompareService();
                mainPanel.setCenter(null);
                mainPanel.setBottom(bottom);
                Config.isOpenCompareData = true;
                leftPanelController.clearControl();
                compareService.compareDatabase(databaseModel) ;
                transformTreeItem(compareService.getChangeDatabase());
                leftPanelController.compareService = compareService;
                leftPanelController.xmlService = xmlService;
            }
        }
    }



    @FXML
    private void actionReturn(ActionEvent event) {
        setDisable(false);
        mainPanel.setCenter(null);
        mainPanel.setBottom(null);
        Config.isOpenCompareData = false;
        leftPanelController.clearControl();
        transformTreeItem(Config.databaseModel);
        mainPanel.setLeft(leftPanel);
    }

    /**
     * 菜单栏是否可点击
     * @param value
     */
    private void setDisable(boolean value){
        crateDatabase.setDisable(value);
        saveDatabase.setDisable(value);
        elseSaveDatabase.setDisable(value);
        openDatabase.setDisable(value);
        returnButton.setDisable(!value);
        createIncrementOracleSqlButton.setDisable(!value);
        createIncrementMySQLButton.setDisable(!value);
    }

    /**
     * 数据库对象转化树结构
     * @param databaseModel
     */
    private void transformTreeItem(DatabaseBean databaseModel){
        transformTreeItemService.setTableTree(leftPanelController.table,databaseModel.getTableList());
        transformTreeItemService.setCommonTree(leftPanelController.view,databaseModel.getViewList());
        transformTreeItemService.setCommonTree(leftPanelController.procedure,databaseModel.getProcedureList());
        transformTreeItemService.setCommonTree(leftPanelController.function,databaseModel.getFunctionList());
        transformTreeItemService.setCommonTree(leftPanelController.trigger,databaseModel.getTriggerList());
        transformTreeItemService.setCommonTree(leftPanelController.basicData,databaseModel.getBasicDataList());
        transformTreeItemService.setSequenceTree(leftPanelController.sequence,databaseModel.getSequenceList());
    }


    @FXML
    private void createOracleIncrementSql(ActionEvent event) throws IOException, TemplateException {
        if (Config.isOpenData) {
            DirectoryChooser dc = new DirectoryChooser();
            File file = dc.showDialog(mainPanel.getScene().getWindow());
            if (file!=null) {
                ExportOracleSQLService exportSQLService =  ExportOracleSQLService.getExportOracleSQLService();
                exportSQLService.exportCompleteOracle(CompareService.getCompareService().getAddDatabase(), file,ConstantConfig.ADD);
                exportSQLService.exportAddOracle(CompareService.getCompareService().getUpdateDatabase(),file,ConstantConfig.UPDATE);
                new Alert(Alert.AlertType.NONE, "Oracle增量脚本生成完毕", new ButtonType[]{ButtonType.CLOSE}).show();
            }
        }
    }

    @FXML
    private void crateGamutOracleSQL(ActionEvent event) throws IOException, TemplateException {
        if (Config.databaseName==null)
            saveFile(new ActionEvent());
        if (Config.isOpenData) {
            DirectoryChooser dc = new DirectoryChooser();
            File file = dc.showDialog(mainPanel.getScene().getWindow());
            if (file!=null) {
                ExportOracleSQLService exportSQLService =  ExportOracleSQLService.getExportOracleSQLService();
                exportSQLService.exportCompleteOracle(Config.databaseModel, file,ConstantConfig.CREATE);
                new Alert(Alert.AlertType.NONE, "Oracle全量脚本生成完毕", new ButtonType[]{ButtonType.CLOSE}).show();
            }
        }
    }


    /**
     * MySQL全量脚本生成
     * @param event
     * @throws IOException
     * @throws TemplateException
     */
    @FXML
    private void crateGamutMySQL(ActionEvent event) throws IOException, TemplateException {
        if (Config.databaseName==null)
            saveFile(new ActionEvent());
        if (Config.isOpenData) {
            DirectoryChooser dc = new DirectoryChooser();
            File file = dc.showDialog(mainPanel.getScene().getWindow());
            if (file!=null) {
                ExportMySQLService.getExportMySQLService().exportCompleteMySQL(Config.databaseModel,file,ConstantConfig.CREATE);
                new Alert(Alert.AlertType.NONE, "MySQL全量脚本生成完毕", new ButtonType[]{ButtonType.CLOSE}).show();
            }
        }
    }


    /**
     * MySQL增量脚本生成
     * @param event
     * @throws IOException
     * @throws TemplateException
     */
    @FXML
    private void createMySQLIncrementSql(ActionEvent event) throws IOException, TemplateException {
        if (Config.isOpenData) {
            DirectoryChooser dc = new DirectoryChooser();
            File file = dc.showDialog(mainPanel.getScene().getWindow());
            if (file!=null) {
                ExportMySQLService.getExportMySQLService().exportCompleteMySQL(CompareService.getCompareService().getAddDatabase(), file, ConstantConfig.ADD);
                ExportMySQLService.getExportMySQLService().exportAddMySQL(CompareService.getCompareService().getUpdateDatabase(), file,ConstantConfig.UPDATE);

                new Alert(Alert.AlertType.NONE, "MySQL增量脚本生成完毕", new ButtonType[]{ButtonType.CLOSE}).show();
            }
        }
    }
}
